#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cerrno>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <stdio.h>

#define NUM 1024
const uint16_t port = 8080;
// udp_server
int main()
{
    // 1.创建套接字
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "sock create error:" << errno << std::endl;
        return 1;
    }
    // 2.绑定
    struct sockaddr_in local;
    local.sin_family = AF_INET;
    local.sin_port = htons(port);
    local.sin_addr.s_addr = INADDR_ANY;
    if (bind(sock, (sockaddr *)&local, sizeof(local)) < 0)
    {
        std::cerr << "bind error :" << errno << std::endl;
        return 2;
    }
    // 3. 提供服务
    bool quit = false;

    char buffer[NUM];
    while (!quit)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&peer, &len);
        std::cout << "client# " << buffer << std::endl;
        
        std::string echo = "hello";
        sendto(sock, echo.c_str(), echo.size(), 0, (sockaddr *)&peer, len);
    }
    return 0;
}